package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"actest/library"
)

type JsonResponse struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func checkHandler(w http.ResponseWriter, r *http.Request) {
	content := r.PostFormValue("content")
	w.Header().Set("content-type", "text/json")
	re := library.AcCtx.Query([]rune(content))
	rep := JsonResponse{
		Code: 0,
		Msg:  "success",
		Data: re,
	}
	msg, _ := json.Marshal(&rep)
	w.Write(msg)
}

func setbitHandler(w http.ResponseWriter, r *http.Request) {
	position := r.PostFormValue("position")
	bitValue, _ := strconv.Atoi(r.PostFormValue("bitValue"))
	w.Header().Set("content-type", "text/json")
	positions := []int64{}
	json.Unmarshal([]byte(position), &positions)
	for _, v := range positions {
		library.BitmapCtx.SetBit(v, byte(bitValue))
	}
	rep := JsonResponse{
		Code: 0,
		Msg:  "success",
		Data: nil,
	}
	msg, _ := json.Marshal(&rep)
	w.Write(msg)
}
func existHandler(w http.ResponseWriter, r *http.Request) {
	position, _ := strconv.ParseInt(r.PostFormValue("position"), 10, 64)
	w.Header().Set("content-type", "text/json")
	exist := library.BitmapCtx.IsExist(position)
	rep := JsonResponse{
		Code: 0,
		Msg:  "存在",
		Data: nil,
	}
	if !exist {
		rep.Code = -1
		rep.Msg = "不存在"
	}
	msg, _ := json.Marshal(&rep)
	w.Write(msg)
}
func getbitStrHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("content-type", "text/html")
	str := fmt.Sprintf("%c\n", library.BitmapCtx.GetBytes())
	time.Sleep(3 * time.Second)
	w.Write([]byte(str))
}
func getBitBinary(w http.ResponseWriter, r *http.Request) {
	msg := fmt.Sprintf("%08b\n", library.BitmapCtx.GetBytes())
	w.Write([]byte(msg))
}
func keyCountHandler(w http.ResponseWriter, r *http.Request) {
	content := r.PostFormValue("content")
	w.Header().Set("content-type", "text/json")
	re := library.AcCtx.KeywordsCount([]rune(content))
	rep := JsonResponse{
		Code: 0,
		Msg:  "success",
		Data: re,
	}
	msg, _ := json.Marshal(&rep)
	w.Write(msg)
}

func main() {
	http.HandleFunc("/check", checkHandler)
	http.HandleFunc("/keyCount", keyCountHandler)
	http.HandleFunc("/setBit", setbitHandler)
	http.HandleFunc("/getBitStr", getbitStrHandler)
	http.HandleFunc("/getBitBinary", getBitBinary)
	http.HandleFunc("/exist", existHandler)
	fmt.Println("listen 8888")
	if err := http.ListenAndServe(":8888", nil); err != nil {
		fmt.Println(1231)
		fmt.Println(err.Error())
	}
}
